package es.udc.emarketapp.http.controller.actions.categories;

import es.udc.emarketapp.emarket.model.category.vo.CategoryVO;
import es.udc.emarketapp.emarket.model.categoryFacade.CategoryFacade;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import es.udc.emarketapp.http.view.actionForms.CategoryForm;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.struts.action.DefaultAction;


public class UpdateCategoryAction extends DefaultAction {

    public ActionForward doExecute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException, InternalErrorException, InternalErrorException {

        ActionMessages errors = new ActionMessages();


        /* Get data. */
        CategoryForm categoryForm = (CategoryForm) form;

        Long idCat = categoryForm.getIdCat();
        Long catFather = categoryForm.getCatFather();
        String nomCat = categoryForm.getNomCat();

        CategoryFacade categoryFacade = new CategoryFacade();

        CategoryVO categoryVO = new CategoryVO(idCat, catFather, nomCat);

        try {

            CategoryVO insertedCategoryVO = categoryFacade.createCategory(categoryVO);
            request.setAttribute("category", insertedCategoryVO);

        } catch (InternalErrorException e) {
            errors.add("ProductIdentifier",
            new ActionMessage("ErrorMessages.product.notFound"));
            saveErrors(request, errors);
            System.out.println("Error al actualizar el producto " + e);
        }


        /* Return ActionForward. */
        if (errors.isEmpty()) {
            return mapping.findForward("Success");
        } else {
            saveErrors(request, errors);
            return new ActionForward(mapping.getInput());
        }
    }
}
